<template>
  <div class="product-container">
    <el-card>
      <div class="toolbar">
        <el-form :inline="true" :model="query" class="filter-form">
          <el-form-item label="品牌">
            <el-select v-model="query.brandId" placeholder="选择品牌" clearable   style="width: 150px">
              <el-option
                  v-for="brand in brands"
                  :key="brand.id"
                  :label="brand.name"
                  :value="brand.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="query.productName" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="query.status" placeholder="选择状态" clearable>
              <el-option label="在售" value="1"></el-option>
              <el-option label="下架" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"   @click="handleSearch">搜索</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="success"   @click="openAddDialog">添加商品</el-button>
      </div>

      <el-table
          :data="productList"
          style="width: 100%"
          v-loading="loading"
          :row-key="row => row.productId">
        <el-table-column prop="productId" label="ID" width="80"></el-table-column>
        <el-table-column prop="productName" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="brandId" label="品牌" width="120">
          <template #default="scope">
            {{ getBrandName(scope.row.brandId) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ￥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '在售' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button  type="primary"   @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button   type="danger"   @click="handleDelete(scope.row.productId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :current-page.sync="query.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="query.pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; text-align: right;">
      </el-pagination>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model ="dialogVisible"
        width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="选择品牌" clearable>
            <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :step="0.01" prefix="￥" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="选择状态">
            <el-option label="在售" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="积分" prop="point">
          <el-input-number v-model="form.point" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getProductList, addProduct, updateProduct, deleteProduct } from '@/api/product'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 品牌列表（硬编码）
const brands = [
  { id: 1, name: '华为' },
  { id: 2, name: '小米' },
  { id: 3, name: '阿里巴巴' },
  { id: 4, name: '腾讯' },
  { id: 5, name: '字节跳动' },
  { id: 6, name: '百度' },
  { id: 7, name: '联想' },
  { id: 8, name: '海尔' },
  { id: 9, name: '格力' }
]

const productList = ref([]) // 商品列表
const total = ref(0) // 商品总数
const loading = ref(false) // 表格加载状态

const query = reactive({
  pageNum: 1,
  pageSize: 10,
  brandId: null,
  productName: null,
  status: null
})

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加商品')
const form = reactive({
  productId: null,
  productName: '',
  brandId: null,
  price: 0,
  stock: 0,
  description: '',
  status: 1,
  point: 0
})
const formRef = ref(null)

// 表单校验规则
const rules = {
  productName: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur'}
  ],
  brandId: [
    {required: true, message: '请选择品牌', trigger: 'change'}
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'},
    {type: 'number', min: 0, message: '价格不能小于 0', trigger: 'blur'}
  ],
  stock: [
    {required: true, message: '请输入库存', trigger: 'blur'},
    {type: 'number', min: 0, message: '库存不能小于 0', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ]
}

// 获取商品列表
const getProductListData = async () => {
  loading.value = true
  try {
    const res = await getProductList(query)
    productList.value = res.data.data.records
    total.value = res.data.data.total
  } catch (error) {
    ElMessage.error(error.message || '获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  query.pageNum = 1
  getProductListData()
}

// 重置表单
const resetForm = () => {
  query.brandId = null
  query.productName = null
  query.status = null
  handleSearch()
}

// 分页改变
const handleSizeChange = (newSize) => {
  query.pageSize = newSize
  query.pageNum = 1
  getProductListData()
}

const handleCurrentChange = (newPage) => {
  query.pageNum = newPage
  getProductListData()
}

// 打开添加商品对话框
const openAddDialog = () => {
  dialogTitle.value = '添加商品'
  Object.assign(form, {
    productId: null,
    productName: '',
    brandId: null,
    price: 0,
    stock: 0,
    description: '',
    status: 1,
    point: 0
  })
  dialogVisible.value = true
}

// 打开编辑商品对话框
const openEditDialog = (row) => {
  dialogTitle.value = '编辑商品'
  Object.assign(form, {
    productId: row.productId,
    productName: row.productName,
    brandId: row.brandId,
    price: row.price,
    stock: row.stock,
    description: row.description,
    status: row.status,
    point: row.point || 0
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (form.productId) {
        // 编辑商品
        try {
          await updateProduct(form)
          ElMessage.success('商品更新成功')
          dialogVisible.value = false
          getProductListData()
        } catch (error) {
          ElMessage.error(error.message || '商品更新失败')
        }
      } else {
        // 添加商品
        try {
          await addProduct(form)
          ElMessage.success('商品添加成功')
          dialogVisible.value = false
          getProductListData()
        } catch (error) {
          ElMessage.error(error.message || '商品添加失败')
        }
      }
    } else {
      ElMessage.error('请填写正确的表单信息')
      return false
    }
  })
}

// 删除商品
const handleDelete = (id) => {
  ElMessageBox.confirm(
      '确定要删除该商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await deleteProduct(id)
      ElMessage.success('删除成功')
      getProductListData()
    } catch (error) {
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 根据品牌ID获取品牌名称
const getBrandName = (id) => {
  const brand = brands.find(b => b.id === id)
  return brand ? brand.name : '未知品牌'
}

// 生命周期钩子
onMounted(() => {
  getProductListData()
})
</script>

<style scoped>
.product-container {
  padding: 20px;
  margin-left: 20%;
  width: 101%;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-form .el-form-item {
  margin-right: 20px;
}

.filter-form .el-form-item:last-child {
  margin-right: 0;
}

.dialog-footer {
  text-align: right;
}

.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
